﻿using System;
using System.Configuration;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using mojoPortal.Web.RS.SBM.AppCode.Lib;

namespace mojoPortal.Web.RS.SBM.Controls
{
    public partial class ModalManageInvoiceControl : RSBaseUserControl
    {

        protected void Page_Load(object sender, EventArgs e)
        {
        }

        public void SetControlEnabledState(bool bstate = false)
        {
            RSSBMCommonFunctions.SetControlsEnabledState(UpdatePanelInvoice.ContentTemplateContainer, bstate);
        }
        protected void btnReturn_Click(object sender, EventArgs e)
        {
            mpeModalInvoice.Hide();
            var nameValues = HttpUtility.ParseQueryString(Request.QueryString.ToString());
            nameValues.Set("tabindex", "5");
            string url = Request.Url.AbsolutePath;
            string updatedQueryString = "?" + nameValues.ToString();
            Response.Redirect(url + updatedQueryString);
        }
        protected void btnEditInvoice_Click(object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            if (userIdentity.RSCanWrite)
            {
                btnEditInvoice.Visible = false;
                btnSaveInvoice.Visible = true;
                btnRemoveInvoice.Visible = true;
                SetControlEnabledState(true);
            }
            else
            {
                lblMessage.Text = "You Do Not Have Permission To Perform This Action!";
                lblMessage.ForeColor = System.Drawing.Color.DarkRed;
                btnEditInvoice.Visible = false;
                btnSaveInvoice.Visible = false;
                btnRemoveInvoice.Visible = false;
                SetControlEnabledState(false);
            }
        }

        protected void btnSaveInvoice_Click(object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            if (userIdentity.RSCanWrite)
            {
                int CompanyId = userIdentity.RSCompanyId;
                int LocationId = hfLocationId.Value == "" ? 0 : Convert.ToInt32(hfLocationId.Value);
                int InvoiceId = txtInvoiceId.Text == "" ? 0 : Convert.ToInt32(txtInvoiceId.Text);
                int WorkOrderId = txtWorkOrderId.Text == "" ? 0 : Convert.ToInt32(txtWorkOrderId.Text);

                string CreateDate = txtCreateDate.Text.Trim();
                string DueDate = txtDueDate.Text.Trim();
                string SentDate = txtSentDate.Text.Trim();
                string Comment = txtComment.Text.Trim();
                float AdditionalDiscountAmount = txtAdditionalDiscountAmount.Text == "" ? 0 : Convert.ToSingle(txtAdditionalDiscountAmount.Text);
                float AdditionalFeeAmount = txtAdditionalFeeAmount.Text == "" ? 0 : Convert.ToSingle(txtAdditionalFeeAmount.Text);
                int TaxPercent = txtTaxPercent.Text == "" ? 0 : Convert.ToInt32(txtTaxPercent.Text);

                int StatusId = Convert.ToInt32(ddlInvoiceStatus.SelectedValue);

                SqlCommand sqlCmd = new SqlCommand();

                SQLHelper.AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@Comment", SqlDbType.NVarChar, -1, ParameterDirection.Input, Comment);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@AdditionalDiscountAmount", SqlDbType.Money, 0, ParameterDirection.Input, AdditionalDiscountAmount);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@AdditionalFeeAmount", SqlDbType.Money, 0, ParameterDirection.Input, AdditionalFeeAmount);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@TaxPercent", SqlDbType.SmallInt, 0, ParameterDirection.Input, TaxPercent);
                if (CreateDate.Trim().Length > 0)
                    SQLHelper.AddParamToSQLCmd(sqlCmd, "@CreateDT", SqlDbType.DateTime, 0, ParameterDirection.Input, Convert.ToDateTime(CreateDate));
                if (DueDate.Trim().Length > 0)
                    SQLHelper.AddParamToSQLCmd(sqlCmd, "@DueDT", SqlDbType.DateTime, 0, ParameterDirection.Input, Convert.ToDateTime(DueDate));
                if (SentDate.Trim().Length > 0)
                    SQLHelper.AddParamToSQLCmd(sqlCmd, "@SentDT", SqlDbType.DateTime, 0, ParameterDirection.Input, Convert.ToDateTime(SentDate));

                SQLHelper.AddParamToSQLCmd(sqlCmd, "@StatusId", SqlDbType.Int, 0, ParameterDirection.Input, StatusId);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@InvoiceId", SqlDbType.Int, 0, ParameterDirection.Input, InvoiceId);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@WorkOrderId", SqlDbType.Int, 0, ParameterDirection.Input, WorkOrderId);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@LocationId", SqlDbType.Int, 0, ParameterDirection.Input, LocationId);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@CompanyId", SqlDbType.Int, 0, ParameterDirection.Input, CompanyId);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@CurrentUser", SqlDbType.NVarChar, 25, ParameterDirection.Input, userIdentity.RSCurrentUser);
                SQLHelper.SetCommandType(sqlCmd, CommandType.StoredProcedure, "rs_uspSaveInvoice");
                SQLHelper.ExecuteScalarCmd(sqlCmd);

                int returnValue = Convert.ToInt32(sqlCmd.Parameters["@ReturnValue"].Value);
                lblMessage.Text = "Invoice Successfully Saved!";
                lblMessage.ForeColor = System.Drawing.Color.DarkBlue;
                hfRedirectURL.Value = Request.RawUrl;
            }
            else
            {
                lblMessage.Text = "You Do Not Have Permission To Perform This Action!";
                lblMessage.ForeColor = System.Drawing.Color.DarkRed;
                hfRedirectURL.Value = "";
            }
            btnEditInvoice.Visible = false;
            btnSaveInvoice.Visible = false;
            btnRemoveInvoice.Visible = false;
            SetControlEnabledState(false);
        }

        protected void btnRemoveInvoice_Click(object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            if (userIdentity.RSCanWrite && userIdentity.RSCanDelete)
            {
                int CompanyId = userIdentity.RSCompanyId;
                int LocationId = hfLocationId.Value == "" ? 0 : Convert.ToInt32(hfLocationId.Value);
                int InvoiceId = txtInvoiceId.Text == "" ? 0 : Convert.ToInt32(txtInvoiceId.Text);
                int WorkOrderId = txtWorkOrderId.Text == "" ? 0 : Convert.ToInt32(txtWorkOrderId.Text);

                if (CompanyId > 0 && InvoiceId > 0 && WorkOrderId > 0)
                {
                    SqlCommand sqlCmd = new SqlCommand();
                    SQLHelper.AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
                    SQLHelper.AddParamToSQLCmd(sqlCmd, "@companyid", SqlDbType.Int, 0, ParameterDirection.Input, CompanyId);
                    SQLHelper.AddParamToSQLCmd(sqlCmd, "@invoiceid", SqlDbType.Int, 0, ParameterDirection.Input, InvoiceId);
                    SQLHelper.AddParamToSQLCmd(sqlCmd, "@WorkOrderid", SqlDbType.Int, 0, ParameterDirection.Input, WorkOrderId);
                    SQLHelper.SetCommandType(sqlCmd, CommandType.Text, "DELETE FROM rs_tblInvoice WHERE InvoiceId=@InvoiceId AND workorderid=@WorkOrderId AND CompanyId=@companyid");
                    SQLHelper.ExecuteScalarCmd(sqlCmd);
                    int returnValue = Convert.ToInt32(sqlCmd.Parameters["@ReturnValue"].Value);
                    lblMessage.Text = "Invoice Successfully Deleted!";
                    lblMessage.ForeColor = System.Drawing.Color.DarkBlue;
                    hfRedirectURL.Value = Request.RawUrl;
                }
            }
            else
            {
                lblMessage.Text = "You Do Not Have Permission To Perform This Action!";
                lblMessage.ForeColor = System.Drawing.Color.DarkRed;
                hfRedirectURL.Value = "";
            }
            btnEditInvoice.Visible = false;
            btnSaveInvoice.Visible = false;
            btnRemoveInvoice.Visible = false;
            SetControlEnabledState(false);
        }

        public void ShowModal(int companyid, int invoiceid)
        {
            hfRedirectURL.Value = "";
            lblMessage.Text = "Invoice";

            if(LoadInvoiceDataByID(companyid, invoiceid))
            {
                btnEditInvoice.Visible = true;
                btnSaveInvoice.Visible = false;
                btnRemoveInvoice.Visible = false;
                SetControlEnabledState(false);
            }
            else
            {
                btnEditInvoice.Visible = false;
                btnSaveInvoice.Visible = true;
                btnRemoveInvoice.Visible = false;
                SetControlEnabledState(true);
            }
            mpeModalInvoice.Show();
        }

        private bool LoadInvoiceDataByID(int companyid, int invoiceid)
        {
            bool bHaveData = false;
            int locationid = RSSBMCommonFunctions.GetLocationIDByInvoiceID(companyid, invoiceid);
            if (companyid > 0 && locationid > 0)
            {
                RSSBMDataLookupLoader.LoadStatusDDL(companyid, "INVOICE_CAT", ddlInvoiceStatus);

                if (invoiceid > 0)
                {
                    String strSQL = "SELECT i.InvoiceId,i.WorkOrderTotalMaterialCost_CF,i.WorkOrderTotalLaborCost_CF,i.WorkOrderTotalCost_CF,i.AdditionalFeeAmount,i.AdditionalDiscountAmount,i.BalanceDue_CF,i.TaxPercent,i.StatusId,i.WorkOrderId,i.LocationId,i.BillingContactId,i.CompanyId,i.CreateDT,i.DueDT,i.SentDT,i.Comment, (select p.DepositAmount from rs_tblWorkOrder p where p.workorderid=i.WorkOrderId) AS DepositAmount  FROM rs_tblInvoice i WHERE i.InvoiceId=@InvoiceId AND i.CompanyId=@CompanyId";
                    SqlCommand myCommand;
                    SqlParameter param;
                    SqlConnection myConnection;
                    myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[GetRSCompanyConnectionString()].ToString());
                    myCommand = new SqlCommand(strSQL, myConnection);
                    SqlDataReader myDataReader;

                    param = new SqlParameter();
                    param.SqlDbType = SqlDbType.Int;
                    param.ParameterName = "@Invoiceid";
                    param.Value = invoiceid;
                    myCommand.Parameters.Add(param);


                    param = new SqlParameter();
                    param.SqlDbType = SqlDbType.Int;
                    param.ParameterName = "@Companyid";
                    param.Value = companyid;
                    myCommand.Parameters.Add(param);

                    myConnection.Open();
                    myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
                    if (myDataReader.HasRows)
                    {
                        myDataReader.Read();
                        txtInvoiceId.Text = myDataReader["InvoiceId"].ToString();

                        if (myDataReader["CreateDT"] != DBNull.Value)
                        {
                            DateTime createdt = Convert.ToDateTime(myDataReader["CreateDT"].ToString());
                            txtCreateDate.Text = createdt.ToShortDateString();
                        }
                        if (myDataReader["SentDT"] != DBNull.Value)
                        {
                            DateTime sentdt = Convert.ToDateTime(myDataReader["SentDT"].ToString());
                            txtSentDate.Text = sentdt.ToShortDateString();
                        }
                        if (myDataReader["DueDT"] != DBNull.Value)
                        {
                            DateTime duedt = Convert.ToDateTime(myDataReader["DueDT"].ToString());
                            txtDueDate.Text = duedt.ToShortDateString();
                        }


                        txtComment.Text = myDataReader["Comment"].ToString();
                        if (myDataReader["StatusId"] != DBNull.Value)
                            ddlInvoiceStatus.SelectedValue = myDataReader["StatusId"].ToString();

                        txtTotalLaborCost.Text = myDataReader["WorkOrderTotalLaborCost_CF"].ToString();
                        txtTotalMaterialCost.Text = myDataReader["WorkOrderTotalMaterialCost_CF"].ToString();
                        txtTotalCost.Text = myDataReader["WorkOrderTotalCost_CF"].ToString();
                        txtAdditionalDiscountAmount.Text = myDataReader["AdditionalDiscountAmount"].ToString();
                        txtAdditionalFeeAmount.Text = myDataReader["AdditionalFeeAmount"].ToString();
                        txtTaxPercent.Text = myDataReader["TaxPercent"].ToString();
                        txtBalanceDue.Text = myDataReader["BalanceDue_CF"].ToString();

                        if (myDataReader["workorderid"] != DBNull.Value)
                            txtWorkOrderId.Text = myDataReader["workorderid"].ToString();
                        if (myDataReader["BillingContactId"] != DBNull.Value)
                            txtBillingContactId.Text = myDataReader["BillingContactId"].ToString();

                        if (myDataReader["DepositAmount"] != DBNull.Value)
                            txtDepositAmount.Text = myDataReader["DepositAmount"].ToString();
                        bHaveData = true;
                    }

                    myConnection.Close();
                }
            }
            return bHaveData;
        }

    }
}